package com.algorithm;

/**
 * 环形链表 II
 */
public class LinkedListCycleIi {

    public static ListNode detectCycle(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode slow = head;
        ListNode fast = head;
        boolean isCycle = false;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                isCycle = true;
                break;
            }
        }

        if (!isCycle){
            return null;
        }

        fast=head;
        while(slow!=fast){
            slow=slow.next;
            fast=fast.next;
        }
        return slow;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(3, new ListNode(4, new ListNode(0, new ListNode(-4))));
        ListNode listNode = detectCycle(head);
        System.out.println(listNode);
    }
}
